//
//  MyViewController.m
//  Funny
//
//  Created by dllo on 15/10/27.
//  Copyright © 2015年 King. All rights reserved.
//

#import "MyViewController.h"

@interface MyViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,MyCollectionViewCellDelegate>

@property (nonatomic, strong) UISegmentedControl *segment;
@property (nonatomic, strong) DataBase *dataBase;
@property (nonatomic, strong) UICollectionView *collection;
@property (nonatomic, strong) NSArray *arr;
@property (nonatomic, assign) BOOL isOpen;
@property (nonatomic, assign) NSInteger flag;

@end

@implementation MyViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isOpen = YES;
    self.flag = 0;
    // 背景图片
    UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth / 3 * 2)];
    [self.view addSubview:image];
    image.image = [UIImage imageNamed:@"background.png"];
    
    // 删除按钮
    UIButton *deleteClick = [UIButton buttonWithFrame:CGRectMake(15, 30, 30, 30) color:nil title:nil type:UIButtonTypeSystem target:self action:@selector(deleteClickWithBtn:) event:UIControlEventTouchUpInside cornerRadius:0];
    [self.view addSubview:deleteClick];
    [deleteClick setBackgroundImage:[UIImage imageNamed:@"delete.png"] forState:UIControlStateNormal];
    deleteClick.tintColor = [UIColor whiteColor];
    
    // 设置按钮
    UIButton *setClick = [UIButton buttonWithFrame:CGRectMake(ScreenWidth - 45, 27, 35, 35) color:nil title:nil type:UIButtonTypeSystem target:self action:@selector(setClickWithBtn:) event:UIControlEventTouchUpInside cornerRadius:0];
    [self.view addSubview:setClick];
    [setClick setBackgroundImage:[UIImage imageNamed:@"setting.png"] forState:UIControlStateNormal];
    setClick.tintColor = [UIColor whiteColor];
    [self.view addSubview:self.segment];
    [self.view addSubview:self.collection];

    // Do any additional setup after loading the view.
}

// 懒加载 collectionView
- (UICollectionView *)collection
{
    if (!_collection) {
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
        flow.minimumInteritemSpacing = 0;
        flow.minimumLineSpacing = 0;
        flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flow.itemSize = CGSizeMake(ScreenWidth, ScreenHeight - ScreenWidth / 3 * 2 - 30);
        self.collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, ScreenWidth / 3 * 2 + 30, ScreenWidth, ScreenHeight - ScreenWidth / 3 * 2 - 30) collectionViewLayout:flow];
        self.collection.backgroundColor = [UIColor whiteColor];
        self.collection.scrollEnabled = NO;
        self.collection.delegate = self;
        self.collection.dataSource = self;
        [self.collection registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    }
    return _collection;
}

// collectionViewCell的协议方法 负责传递 cityID 打开收藏页面详细信息
- (void)pushToNextWithModel:(id)Model
{
    if (_flag == 0) {
        FoodDetailViewController *cityVC = [FoodDetailViewController shareViewController];
        NSLog(@"%@",Model);
        cityVC.ID = Model;
        [self presentViewController:cityVC animated:NO completion:^{
            
        }];
    }
    if (_flag == 1) {
        CityIntroductionViewController *cityVC = [CityIntroductionViewController shareViewController];
        cityVC.cityID = Model;
        NSLog(@"%@",Model);
        [self presentViewController:cityVC animated:NO completion:^{
            
        }];
    }
    if (_flag == 2) {
        DetailViewController *cityVC = [DetailViewController shareViewController];
        cityVC.productId = Model;
        [self.navigationController pushViewController:cityVC animated:YES];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 3;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.arr = self.arr.mutableCopy;
    cell.delegate = self;
    return cell;
}

- (NSArray *)arr
{
    if (!_arr) {
        self.arr = [NSArray array];
    }
    return _arr;
}

- (DataBase *)dataBase
{
    if (!_dataBase) {
        self.dataBase = [DataBase shareDataBase];
    }
    return _dataBase;
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.dataBase open];
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = NO;
    switch (_segment.selectedSegmentIndex) {
        case 0:
            self.arr = [self.dataBase getInlandAll];
            break;
        case 1:
            self.arr = [self.dataBase getAll];
            break;
        case 2:
            self.arr = [self.dataBase getDetailAll];
            break;
        default:
            break;
    }
    [_collection reloadData];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self.dataBase close];
}

// 收藏列表的控制segment
- (UISegmentedControl *)segment
{
    if (!_segment) {
        self.segment = [[UISegmentedControl alloc]initWithItems:@[@"国内",@"国际",@"周边"]];
        _segment.frame = CGRectMake(0, ScreenWidth / 3 * 2 , ScreenWidth, 30);
        _segment.selectedSegmentIndex = 0;
        _segment.backgroundColor = [UIColor whiteColor];
        _segment.tintColor = [UIColor grayColor];
        [_segment addTarget:self action:@selector(segmentClickWithSeg:) forControlEvents:UIControlEventValueChanged];
    }
    return _segment;
}

// 选择打开不同的数据库 给collectionView传入不同的数组
- (void)segmentClickWithSeg:(UISegmentedControl *)seg
{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"delete" object:nil userInfo:@{@"do":@1}];
    self.collection.contentOffset = CGPointMake(_segment.selectedSegmentIndex * ScreenWidth, 0) ;
    NSInteger index = _segment.selectedSegmentIndex;
    switch (index) {
        case 0:
            [[NSNotificationCenter defaultCenter]postNotificationName:@"change" object:nil userInfo:@{@"if":@"0"}];
            self.arr = [self.dataBase getInlandAll];
            [self.collection reloadData];
            self.flag = 0;
            break;
        case 1:
            [[NSNotificationCenter defaultCenter]postNotificationName:@"change" object:nil userInfo:@{@"if":@"1"}];
            self.arr = [self.dataBase getAll];
            [self.collection reloadData];
            self.flag = 1;
            break;
        case 2:
            [[NSNotificationCenter defaultCenter]postNotificationName:@"change" object:nil userInfo:@{@"if":@"2"}];
            self.arr = [self.dataBase getDetailAll];
            [self.collection reloadData];
            self.flag = 2;
            break;
        default:
            break;
    }
}

// 设置按钮 清除缓存 关于我们
- (void)setClickWithBtn:(UIButton *)btn
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"设置" message:nil preferredStyle:0];
    UIAlertAction *cleanAction = [UIAlertAction actionWithTitle:@"清除缓存" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [[SDImageCache sharedImageCache]setMaxCacheAge:20240]; // 最大缓存图片大小
        CGFloat size = [[SDImageCache sharedImageCache]getSize]; // 当前缓存图片大小
        NSString *str = [NSString stringWithFormat:@"缓存:%.2fM",size / 1024 / 1024];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:str preferredStyle:1];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [[SDImageCache sharedImageCache]clearDisk]; // 清楚缓存图片
            NSString *strPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]; // 缓存网络请求路径
            NSFileManager *manger = [NSFileManager defaultManager];
            [manger removeItemAtPath:strPath error:nil]; // 按路径删除
            [self MBprogrammerHUDWithStr:@"清除缓存"];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:okAction];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *usAction = [UIAlertAction actionWithTitle:@"关于我们" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        AboutUsViewController *aboutVC = [AboutUsViewController shareViewController];
        [self presentViewController:aboutVC animated:NO completion:^{
            
        }];
    }];

    [alert addAction:cancelAction];
    [alert addAction:usAction];
    [alert addAction:cleanAction];
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}

// 点击删除按钮 通知collectionView 里的tableView 进行操作
- (void)deleteClickWithBtn:(UIButton *)btn
{
    if (self.arr.count == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"暂时还无收藏" preferredStyle:1];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:okAction];
    }
    if (_isOpen) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"delete" object:nil userInfo:@{@"do":@0}];
    }else{
        [[NSNotificationCenter defaultCenter]postNotificationName:@"delete" object:nil userInfo:@{@"do":@1}];
    }
    _isOpen = !_isOpen;
}

// 菊花
- (void)MBprogrammerHUDWithStr:(NSString *)str
{
    MBProgressHUD *hud = [[MBProgressHUD alloc]initWithView:self.view];
    hud.labelText = str;
    [self.view addSubview:hud];
    [hud showAnimated:YES whileExecutingBlock:^{
        sleep(1);
    } completionBlock:^{
        [hud removeFromSuperview];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
